<template>
  <div>
    <!-- Tree树形控件 -->
    <el-tree
      :data="roleMenus"
      :props="defaultProps"
      @node-click="handleNodeClick"
      ref="menu-tree"
      show-checkbox
      default-expand-all
      :default-checked-keys="checkedIds"
      node-key="id"
    ></el-tree>
    <el-button type="primary" @click="onSave">保存</el-button>
    <el-button @click="handleClear">清空</el-button>
  </div>
</template>

<script>
//1.导入接口
import { getRoleMenus, setRoleMenus } from "@/api/role";
export default {
  name: "RoleAllocMenu",
  props: {
    roleId: {
      type: [String, Number],
      required: true,
    },
  },
  data() {
    return {
      //2.用于存储接口函数返回的角色菜单信息
      roleMenus: [],
      defaultProps: {
        children: "subMenuList",
        label: "name",
      },
      checkedIds: [],
    };
  },
  created() {
    this.loadRoleMenus();
  },
  methods: {
    //3.封装获取角色菜单信息的方法
    loadRoleMenus() {
      getRoleMenus(this.roleId).then((res) => {
        if (res.data.code === "000000") {
          console.log("分配菜单", res);
          this.roleMenus = res.data.data;
          const checkedIds = this.getSelectedIds(res.data.data);
          console.log("状态为true的菜单id", checkedIds);
          this.checkedIds = checkedIds;
          //等下一个渲染周期再执行里面的代码
          //其实就是等上面复选框树渲染完毕后再执行
          //1法
          //setTimeout(() => {
          //   this.$refs["menu-tree"].setCheckedKeys(checkedIds);
          // }, 0);
          //2法
          // this.$nextTick(() => {
          //   this.$refs["menu-tree"].setCheckedKeys(checkedIds);
          // });
        } else {
          this.$message.error("获取角色信息失败...");
        }
      });
    },
    //4.把接口返回的菜单信息,过滤得到标记为true的id数组
    getSelectedIds(menuArr) {
      let ids = [];
      menuArr.forEach((menu) => {
        //规则1、如果菜单有子菜单，就只考虑子菜单，他自己的状态就不考虑了
        //规则2、如果菜单无子菜单,并且标记为true，就保存他的id
        if (menu.subMenuList) {
          const tmpArr = this.getSelectedIds(menu.subMenuList);
          //ids=[...ids,...tmpArr]
          ids = ids.concat(tmpArr);
        } else if (menu.selected) {
          ids.push(menu.id);
        }
      });
      return ids;
    },
    //5清空所有选项
    handleClear() {
      this.$refs["menu-tree"].setCheckedKeys([]);
    },
    //6点击保存,给角色分配选中的菜单项
    onSave() {
      const data = {
        roleId: this.roleId,
        menuIdList: this.$refs["menu-tree"].getCheckedKeys(),
      };
      setRoleMenus(data).then((res) => {
        if (res.data.code === "000000") {
          this.$message.success("给角色分配菜单操作成功!");
          this.$router.push({ name: "roles" });
        } else {
          this.$message.error("分配菜单操作失败~");
        }
      });
    },

    handleNodeClick(data) {
      console.log(data);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-tree {
  margin-bottom: 20px;
}
</style>
